﻿using System;
using System.Collections.Generic;
using System.Reflection;
using KuiHuaBaoDian.Services.Guide;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

namespace KuiHuaBaoDian.GuideGraph.Editor {

    public class GuideGraphSearchMenuWindowProvider : ScriptableObject, ISearchWindowProvider {

        public delegate bool OnSelectEntryDelegate(SearchTreeEntry searchTreeEntry, SearchWindowContext context);

        public OnSelectEntryDelegate SelectEntry;

        public List<SearchTreeEntry> CreateSearchTree(SearchWindowContext context) {
            var entryList = new List<SearchTreeEntry> {
                new SearchTreeGroupEntry(new GUIContent("创建新节点")),
            };
            entryList.Add(new SearchTreeGroupEntry(new GUIContent("触发")) { level = 1 });
            entryList.Add(new SearchTreeGroupEntry(new GUIContent("条件")) { level = 2 });
            AddEntry(3, entryList, new Type[] { typeof(GuideTrigger) });
            entryList.Add(new SearchTreeGroupEntry(new GUIContent("逻辑")) { level = 2 });
            AddEntry(3, entryList, new Type[] { typeof(GuideTriggerAnd) });
            entryList.Add(new SearchTreeGroupEntry(new GUIContent("步骤")) { level = 1 });
            AddEntry(2, entryList, new Type[] { typeof(IGuideStep) });
            //entryList.Add(new SearchTreeGroupEntry(new GUIContent("输入")) { level = 1 });
            //AddEntry(2, entryList, new Type[] { typeof(IGuideEntityHasInput) }, new Type[] { typeof(IGuideTrigger), typeof(IGuideTriggerEnd) });
            return entryList;
        }

        public bool OnSelectEntry(SearchTreeEntry searchTreeEntry, SearchWindowContext context) {
            if (SelectEntry == null) {
                return false;
            }
            return SelectEntry(searchTreeEntry, context);
        }

        private void AddEntry(int level, List<SearchTreeEntry> entryList, Type[] targetTypes, Type[] excludeTypes = null) {
            excludeTypes ??= new Type[0];
            var itor = GuideGraphTypeUtility.GetTypeEnumerable(targetTypes, excludeTypes);
            foreach (var type in itor) {
                var titleAttribute = type.GetCustomAttribute<NodeTitleAttribute>();
                var label = titleAttribute != null ? titleAttribute.Value : type.Name;
                entryList.Add(new SearchTreeEntry(new GUIContent(label)) { level = level, userData = type });
            }
        }
    }
}
